/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DAL;

import BE.Song;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Zalan
 */
public class SongsDBManager {
     private final DBConnectionManager cm;
     
     private static SongsDBManager instance = null;

    public static SongsDBManager getInstance() throws IOException {
      
       if(instance == null)
       {
           instance = new SongsDBManager();
       }
       return instance;
    }
    
    private SongsDBManager() throws IOException
    {
        cm = DBConnectionManager.getInstance();
    }
    
     public Song getOneSong(ResultSet rs) throws SQLException
    {
        int id = rs.getInt("Id");
        String title = rs.getString("Title"); 
        int artistId = rs.getInt("ArtistId");
        int categoryId = rs.getInt("CategoryId");
        int bpm = rs.getInt("BPM");
        int duration = rs.getInt("Duration");
        boolean favorite = rs.getBoolean("Favourite");
        
        Song sng = new Song(id, title, artistId, categoryId, bpm, duration, favorite);
        return sng;
    }
     
      public Song getById(int songId) throws SQLException
    {
        try (Connection con = cm.getConnection())
        {
            String sql = "SELECT Song.*, Artist.Name, Category.Category "
                    + " FROM Song JOIN Artist ON Song.ArtistID = Artist.ID "
                    + " JOIN Category ON Song.CategoryID = Category.ID "
                    + " WHERE Song.ID = ? ";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setInt(1, songId);

            ResultSet rs = ps.executeQuery();
            if (rs.next()) // check if get song id
            {
                return getOneSong(rs);
            }
            else
            {
                return null;
            }
        }
    }
}
